+function ($) {
    'use strict';
    var MultipleFileInput = function (element, options) {
        this.$element = $(element)
        this.options = options
        this.init();
    }

    MultipleFileInput.DEFAULTS = {
        imgInfo:[],
        dataField: 'list',
        width: 180,
        height: 150,
        allowedType: ['png', 'jpg', 'jpeg', 'gif', 'bmp','mp4','mp3','doc','docx'],
        imageType:['png', 'jpg', 'jpeg', 'gif', 'bmp'],
        maxSize : "5M",
        previewUrl: undefined,
        delUrl:undefined
    };

    MultipleFileInput.prototype.init = function () {
        this.initContainer();
        this.initChange();
        this.bindDelAction();
    };
    MultipleFileInput.prototype.initContainer = function () {
        this.$container = $([
            '<div class="multiple-file">',
            '<div class="multiple-upload">',
            '<button type="button" class="btn btn-success">' ,
            '<i class="fa fa-cloud-upload" aria-hidden="true"></i>上传附件</button>',
            '</div>',
            '<div class="display swiper-container  display-container">',
            '<ul class="display clearfloat swiper-wrapper">',
            '</ul>',
            '<div class="swiper-button-prev"></div>',
            '<div class="swiper-button-next"></div>',
            ' </div>',
            '</div>'
        ].join(''));
        this.$container.insertAfter(this.$element);
        this.$fileContainer = this.$container.find('.multiple-upload');
        this.$displaycontainer = this.$container.find('.display-container');
        this.$fileContainer.append(this.$element);
        new Swiper ('.swiper-container', {
            observer:true,
            observeParents:true,
            slidesPerView : 4,
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev'
            }
        })
    };

    MultipleFileInput.prototype.initChange = function () {
        var mergeOption = this.options,
            maxSize = mergeOption.maxSize,
            self = this;
        this.$element.change(function () {
            if(this.files&&this.files[0]){
                self.fileJson = this.files[0];
                self.filetype = Bolt.getFileType(self.fileJson);
                if((mergeOption.allowedType).indexOf(self.filetype) == -1){
                    Bolt.notify('error',"文件格式不合法只能上传图片视频音频doc文件");
                    return ;
                }
                if(self.fileJson.size>Bolt.sizeToByte(maxSize)){
                    Bolt.notify('error',"单个文件不能超过"+maxSize);
                    return ;
                }
                else{
                    var obj = new FileReader();//新建读取文件对象
                    obj.readAsDataURL( self.fileJson );//读取文件
                    obj.onload = function(){
                        var result = this.result;
                        mergeOption.imgInfo.push({id:"",title:self.fileJson.name,size:self.fileJson.size,type:self.filetype,value:result});
                        self.initSource(result,1);
                    }
                }
            }
        })
    };
    MultipleFileInput.prototype.getSource=function () {
        var values = [];
        $.each(this.options.imgInfo,function(index,value){
            if(value['id'] == ''){
                values.push(value);
            }
        });
        return values;
    };

    MultipleFileInput.prototype.initPreview = function(param){
        var $that = this;
        if (!(param||this.options.previewUrl)) {
            return;
        }
        var render =  template.compile(this.options.previewUrl), previewUrl = render(param)

        Bolt.ajax('doajax', {
            type:'GET',
            url: previewUrl,
            loadingMask: true,
            okCallback: function (data) {
                data = data[$that.options.dataField];
                $that.options.imgInfo = data
                $.each(data, function (i, row) {
                    if(!row['value']){
                        return;
                    }
                    if(row.type){
                        $that.initSource(row,0)
                    }else{
                       var arr = row['value'].split(',');
                            if(arr.length>1) {
                               var  type = arr[0].match(/([^/]*);/)[1]
                                row.type = type
                                row.value = arr[1];
                            }
                        $that.initSource(row,0)
                    }
                })

            }
        })
    };

    MultipleFileInput.prototype.initSource=function (result,flag) {
        //flag:true是添加，false是编辑
        var $Li = $("<li class='source'></li>"),$Source;
        if(['doc','docx'].indexOf(this.filetype) != -1||['doc','docx'].indexOf(result.type) != -1){
            $Source = $("i.iconfont");
        } else{
            if(this.options.imageType.indexOf(this.filetype) != -1||this.options.imageType.indexOf(result.type) != -1){
                //    如果是图片
                $Source = $("<img>")
            }
            else if(this.filetype=='mp3'||result.type=='mp3'){
                //    如果是mp3
                $Source = $('<audio  controls preload="none"></audio>');
            }
            else if(this.filetype=='mp4'||result.type=='mp4'){
                //    如果是mp4
                $Source = $('<video controls></video>');
            }
            if(flag){
                $Source.attr('src',result);
            }
            else{
                var pin_result='';
                if(this.options.imageType.indexOf(result.type) != -1){
                    pin_result = 'data:image/'+(result.type=='jpg'?'jpeg':result.type)+';base64,'+result.value;
                }
                else if(result.type=='mp3'){
                    pin_result = 'data:audio/'+result.type+';base64,'+result.value;
                }
                else if(result.type=='mp4'){
                    pin_result = 'data:video/'+result.type+';base64,'+result.value;
                }
                $Source.attr('src',pin_result);
            }
        }
        $Source.width(this.options.width);
        $Source.height(this.options.height);
        if(result.name){
            var imgname = flag?(this.fileJson.name):(result.name);
            $Li.append($Source).append("<p class='clearfloat'><span>"+imgname+"</span><i class='del fr'>✖</i></p>")
        }else{
            $Li.append($Source).append("<p class='clearfloat'><i class='del fr'>✖</i></p>")
        }
        if(flag){
            $Li.data("id","");
            $Li.data("filetype",this.filetype);
        }
        else{
            $Li.data("id",result.id);
            $Li.data("filetype",result.type);
        }
        this.$displaycontainer.find('ul').append($Li);
        this.$displaycontainer.show();
        this.hoverfunc();
    };

    MultipleFileInput.prototype.hoverfunc=function () {
        this.$displaycontainer.find('ul').on("mouseenter mouseleave",">li.source",function (e) {
            if(e.type=='mouseenter'){
                $(this).find(">p").slideDown(500)
            }else if(e.type=='mouseleave'){
                $(this).find(">p").slideUp(500)
            }
        })
    }

    MultipleFileInput.prototype.bindDelAction=function () {
        var self = this;
        this.$displaycontainer.find('ul').on("click",">li>p>i.del",function () {
            var sourceId = $(this).parents("li.source").data("id"),
                $Li = $(this).parents("li.source"),
                Li_index = $Li.index();
            if(sourceId && self.options.delUrl){
                Bolt.ajax('doajax', {
                    url:self.options.delUrl,
                    data:{id:sourceId},
                    confirmMsg:"确定要删除此项吗?",
                    loadingMask: true,
                    okCallback: function (res){
                        $Li.remove();
                        self.options.imgInfo.splice(Li_index,1);
                    }
                })
            }
            else{
                $Li.remove();
                self.mergeOption.imgInfo.splice(Li_index,1);
            }
            if(!self.mergeOption.wrap.children("li.source").length){
                self.mergeOption.options.hide();
            }
        })
    }

    function Plugin (option) {
        var value,
            args = Array.prototype.slice.call(arguments, 1);
        this.each(function () {
            var $this = $(this),
                data = $this.data('bolt.multipleFileInput'),
                options = $.extend({}, MultipleFileInput.DEFAULTS, $this.data(),  typeof option === 'object' && option);

            if (typeof option === 'string') {

                if (!data) {
                    return;
                }
                value = data[option].apply(data, args);
                if (option === 'destroy') {
                    $this.removeData('bolt.multipleFileInput');
                }
            }

            if (!data) {
                $this.data('bolt.multipleFileInput', (data = new MultipleFileInput(this, options)));
            }
        });
        return typeof value === 'undefined' ? this : value;
    };



    $.fn.multipleFileInput = Plugin
    $.fn.multipleFileInput.Constructor = MultipleFileInput;
    $.fn.multipleFileInput.defaults = MultipleFileInput.DEFAULTS;


    Bolt.addComponent({
        name: "MultipleFileInput",
        plugin: Plugin,
        runPoint: Bolt.eventType.afterAjaxPageShow,
        expr: "[data-toggle='multipleFileInput']",
        order: 800
    })

    $(document).on(Bolt.eventType.initUI, function(e) {
        $(e.target).find('[data-toggle="multipleFileInput"]').each(function() {
            var $this = $(this), options = $this.data()
            if (!$this.length) return
            if (options.options && typeof options.options === 'string') options.options = options.options.toObj()
            $.extend(options, typeof options.options === 'object' && options.options)
            Plugin.call($this, options)
        })
    })
}(jQuery);